<template>
  <div class="spider-tasks">
    <div class="header">
      <h2>爬虫任务管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        新建任务
      </el-button>
    </div>

    <div class="search-bar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchText"
            placeholder="搜索任务名称"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="statusFilter" placeholder="任务状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="运行中" value="running" />
            <el-option label="已停止" value="stopped" />
            <el-option label="已完成" value="completed" />
            <el-option label="失败" value="failed" />
          </el-select>
        </el-col>
      </el-row>
    </div>

    <el-table :data="filteredTasks" style="width: 100%" stripe :header-cell-style="{ textAlign: 'center' }" :cell-style="{ textAlign: 'center' }">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="任务名称" />
      <el-table-column prop="url" label="目标URL" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="schedule" label="调度规则" />
      <el-table-column prop="lastRun" label="最后运行" />
      <el-table-column prop="dataCount" label="数据量" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="runTask(scope.row)" 
            :disabled="scope.row.status === 'running'">
            运行
          </el-button>
          <el-button size="small" type="warning" @click="editTask(scope.row)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="deleteTask(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="filteredTasks.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑任务对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="showAddDialog"
      width="600px"
    >
      <el-form :model="taskForm" label-width="100px">
        <el-form-item label="任务名称">
          <el-input v-model="taskForm.name" />
        </el-form-item>
        <el-form-item label="目标URL">
          <el-input v-model="taskForm.url" />
        </el-form-item>
        <el-form-item label="爬取规则">
          <el-input v-model="taskForm.rules" type="textarea" rows="3" 
            placeholder="请输入CSS选择器或XPath规则" />
        </el-form-item>
        <el-form-item label="调度规则">
          <el-select v-model="taskForm.schedule" style="width: 100%">
            <el-option label="手动执行" value="manual" />
            <el-option label="每小时" value="hourly" />
            <el-option label="每天" value="daily" />
            <el-option label="每周" value="weekly" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="taskForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveTask">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const searchText = ref('')
const statusFilter = ref('')
const showAddDialog = ref(false)
const editingTask = ref(null)
const currentPage = ref(1)
const pageSize = ref(20)

const taskForm = ref({
  name: '',
  url: '',
  rules: '',
  schedule: 'manual',
  description: ''
})

const tasks = ref([
  {
    id: 1,
    name: '新闻爬虫',
    url: 'https://news.example.com',
    status: 'running',
    schedule: 'hourly',
    lastRun: '2024-01-15 10:30:00',
    dataCount: 1250,
    rules: '.news-title, .news-content',
    description: '爬取最新新闻'
  },
  {
    id: 2,
    name: '商品价格监控',
    url: 'https://shop.example.com',
    status: 'completed',
    schedule: 'daily',
    lastRun: '2024-01-15 08:00:00',
    dataCount: 850,
    rules: '.price, .product-name',
    description: '监控商品价格变化'
  },
  {
    id: 3,
    name: '股票数据',
    url: 'https://finance.example.com',
    status: 'failed',
    schedule: 'manual',
    lastRun: '2024-01-14 16:45:00',
    dataCount: 0,
    rules: '.stock-price, .stock-name',
    description: '获取股票实时数据'
  }
])

const filteredTasks = computed(() => {
  let result = tasks.value
  
  if (searchText.value) {
    result = result.filter(task =>
      task.name.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }
  
  if (statusFilter.value) {
    result = result.filter(task => task.status === statusFilter.value)
  }
  
  return result
})

const dialogTitle = computed(() => {
  return editingTask.value ? '编辑任务' : '新建任务'
})

const getStatusType = (status) => {
  const types = {
    running: 'success',
    stopped: 'info',
    completed: 'primary',
    failed: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    running: '运行中',
    stopped: '已停止',
    completed: '已完成',
    failed: '失败'
  }
  return texts[status] || status
}

const runTask = (task) => {
  task.status = 'running'
  task.lastRun = new Date().toLocaleString()
  ElMessage.success(`任务 ${task.name} 开始运行`)
  
  // 模拟任务执行
  setTimeout(() => {
    task.status = 'completed'
    task.dataCount += Math.floor(Math.random() * 100) + 50
    ElMessage.success(`任务 ${task.name} 执行完成`)
  }, 3000)
}

const editTask = (task) => {
  editingTask.value = task
  taskForm.value = { ...task }
  showAddDialog.value = true
}

const deleteTask = (task) => {
  ElMessageBox.confirm('确定要删除此任务吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = tasks.value.findIndex(t => t.id === task.id)
    if (index > -1) {
      tasks.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const saveTask = () => {
  if (editingTask.value) {
    // 编辑任务
    const index = tasks.value.findIndex(t => t.id === editingTask.value.id)
    if (index > -1) {
      tasks.value[index] = { ...taskForm.value }
    }
    ElMessage.success('任务更新成功')
  } else {
    // 新建任务
    const newTask = {
      ...taskForm.value,
      id: Date.now(),
      status: 'stopped',
      lastRun: '-',
      dataCount: 0
    }
    tasks.value.push(newTask)
    ElMessage.success('任务创建成功')
  }
  
  showAddDialog.value = false
  editingTask.value = null
  taskForm.value = {
    name: '',
    url: '',
    rules: '',
    schedule: 'manual',
    description: ''
  }
}
</script>

<style scoped>
.spider-tasks {
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
